package com.netty.demo.server.netty.tcp;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 服务初始化配置
 *
 * @author Administrator 余秀良
 * @version 1.0
 * <p>date: 2019年09月09日  12:49 </p>
 * <p>address: 四川成都 </p>
 */
@Component
public class NettyTcpServerInitializer extends ChannelInitializer<SocketChannel> {
    @Resource
    private TcpServerChannelHandler tcpServerChannelHandler;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //优化使用的线程
        final EventExecutorGroup group = new DefaultEventExecutorGroup(16);
        //IdleStateHandler心跳机制,如果超时触发Handle中userEventTrigger()方法
        pipeline.addLast("idleStateHandler", new IdleStateHandler(15, 0, 0, TimeUnit.MINUTES));
        //设置解码器
        pipeline.addLast("tcpDecoder", new TcpRequestDecoder());
        //设置业务处理器
        pipeline.addLast(group, "tcpServerHandler", tcpServerChannelHandler);
    }
}
